package cn.tedu.numbersum;

/**
 * 给出两个 非空 的链表用来表示两个非负的整数。其中，它们各自的位数是按照 逆序 的方式存储的，并且它们的每个节点只能存储 一位 数字。
 * <p>
 * 如果，我们将这两个数相加起来，则会返回一个新的链表来表示它们的和。
 * <p>
 * 您可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 * <p>
 * 示例：
 * <p>
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 * <p>
 */
public class AddTwoNumbers {
    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    private ListNode makeNode(long number) {
        int remainder = (int) (number % 10);
        ListNode node = new ListNode(remainder);
        number /= 10;
        ListNode lastNode = node;
        while (number > 0) {
            remainder = (int) (number % 10);
            lastNode.next = new ListNode(remainder);
            lastNode = lastNode.next;
            number /= 10;
        }
        return node;
    }

    private ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        ListNode p = l1;
        ListNode q = l2;
        int carry = 0;
        ListNode current = res;
        while (p != null || q != null) {
            int sum = carry;
            sum += ((p != null) ? p.val : 0) + ((q != null) ? q.val : 0);
            current.val = sum % 10;
            carry = sum / 10;
            if (p != null)
                p = p.next;
            if (q != null)
                q = q.next;
            current.next = new ListNode(carry);
            current = current.next;
        }

        current = res;
        while (current != null) {
            if (current.next != null && current.next.next == null) {
                if (current.next.val == 0)
                    current.next = null;
            }
            current = current.next;
        }

        return res;
    }

    public static void main(String[] args) {
        AddTwoNumbers inst = new AddTwoNumbers();

        ListNode n1 = inst.makeNode(1);
        ListNode n2 = inst.makeNode(1999999999999999999L);

        ListNode node = inst.addTwoNumbers(n1, n2);
        System.out.println(node);
    }
}
